package org.zjx.team;

import org.zjx.team.teams.FixedTeam;
import org.zjx.team.teams.RandomTeam;
import org.zjx.team.teams.SingleTeam;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TeamManager {
    public static Map<String, ITeam> taskMap = new ConcurrentHashMap<>();

    private static final class InstanceHolder {
        static final TeamManager instance = new TeamManager();
    }

    public static TeamManager getInstance() {
        return InstanceHolder.instance;
    }

    public void add(ITeam team) {
        taskMap.put(team.getTeamId(), team);
    }

    public ITeam getTeam(String teamId) {
        return taskMap.get(teamId);
    }

    public ITeam addTeamMember(String playerId,TeamType teamType) {
        ITeam team = getTeamByPlayer(playerId);
        if (team != null) return team;
        team = getVacancy();
        if (team != null){
            team.addTeamMember(playerId);
            return team;
        }

        if (teamType == TeamType.SINGLE){
            team = new SingleTeam(playerId);
        } else if (teamType == TeamType.RANDOM){
            team = new RandomTeam(playerId);
        }else {
            team = new FixedTeam(playerId);
        }
        taskMap.put(team.getTeamId(),team);
        return team;
    }

    //获取有空缺的队伍
    public ITeam getVacancy() {
        return taskMap.values().stream().filter(ITeam::isVacancy).findFirst().orElse(null);
    }

    //角色是否有队伍
    public ITeam getTeamByPlayer(String playerId) {
        return taskMap.values().stream().filter(team -> team.getTeamMembers().contains(playerId)).findFirst().orElse(null);
    }
}
